package com.jinyang.jetpackdemo.util.http.model

import com.jinyang.jetpackdemo.util.LjyLogUtil
import kotlin.jvm.JvmOverloads
import okhttp3.RequestBody
import okhttp3.FormBody
import org.json.JSONObject
import java.lang.Exception
import kotlin.collections.HashMap

/**
 * @Author: LiuJinYang
 * @CreateDate: 2020/5/16 9:32
 * 参数类
 */
class Parameter : HashMap<String, Any?>() {
    fun add(key: String, value: Any?): Parameter {
        put(key, value)
        return this
    }

    override fun put(key: String, value: Any?): Any? {
        return super.put(key, value)
        //        if (value instanceof String ||value instanceof File ){
//            return super.put(key, value);
//        } else {
//            return super.put(key, String.valueOf(value));
//        }
    }

    fun toParameterString(): String {
        var result = ""
        if (!entries.isEmpty()) {
            for ((key, value) in entries) {
                result = "$result$key=$value&"
            }
            if (result.endsWith("&")) {
                result = result.substring(0, result.length - 1)
            }
        }
        return result
    }

    @JvmOverloads
    fun toPrintString(e: Int = 0) {
        if (!entries.isEmpty()) {
            for ((key, value) in entries) {
                if (e == 0) {
                    LjyLogUtil.d(">>>>>>$key=$value")
                } else {
                    LjyLogUtil.d(">>>>>>$key=$value")
                }
            }
        }
    }

    fun toOkHttpParameter(): RequestBody {
        val requestBody: RequestBody
        val builder = FormBody.Builder()
        for ((key, value) in entries) {
            builder.add(key + "", value.toString() + "")
        }
        requestBody = builder.build()
        return requestBody
    }

    fun toParameterJson(): JSONObject? {
        val result = JSONObject()
        return try {
            if (!entries.isEmpty()) {
                for ((key, value) in entries) {
                    result.put(key, value)
                }
            }
            result
        } catch (e: Exception) {
            null
        }
    }
}